﻿package 
{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.FileFilter;
	import flash.net.URLLoader;
	import flash.display.Loader;
	import flash.text.TextFormat;
	import fl.controls.ProgressBar;
	import fl.controls.ProgressBarMode;
	import flash.display.LoaderInfo;
	import flash.net.navigateToURL;
	import flash.text.TextFieldAutoSize;

	public class FileUpload extends Sprite
	{
		private var _browse:browse_btn;
		private var _upload:upload_btn;
		private var _output:TextField;
		private var _fileReference:FileReference;
		private var loader:Loader;
		private var pictureWidth:Number;
		private var pictureHeight:Number;
		private var infoFormat:TextFormat;
		private var time:Date;
		private var pb:ProgressBar;
		private var sellerid:String="";
		private var shopurl:String="";
		private var percentText:TextField;
		private var fileLoader:URLLoader;
		private function formatSize(size:Number)
		{
			var newSize:Number = size;
			newSize = newSize / 1024;
			if (Math.round(newSize) < 1024)
			{
				return newSize.toFixed(2)+" kB ";
			}
			newSize = newSize / 1024;
			return newSize.toFixed(2)+" MB ";
		}

		private function SWFLoadComplete(e:Event)
		{
			
			var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
			sellerid = String(paramObj["sellerid"])
			shopurl=String(paramObj["shopname"]);
		}
		public function FileUpload()
		{			
			this.addEventListener(Event.ADDED_TO_STAGE, SWFLoadComplete);
			_browse = new browse_btn();
			_browse.addEventListener(MouseEvent.CLICK, browseHandler);
			_browse.x = 40;
			_browse.y = 40;
			addChild(_browse);
			time = new Date();
			trace(time.time);
			_upload = new upload_btn();
			_upload.x = 250;
			_upload.y = 40;
			_upload.visible = false;
			_upload.addEventListener(MouseEvent.CLICK,uploadHandler);
			addChild(_upload);
			infoFormat = new TextFormat();
			infoFormat.font = "Verdana";
			infoFormat.size = 16;
			percentText= new TextField();
			percentText.x = 40;
			percentText.y = 130;

			pb = new ProgressBar();
			pb.height = 50;
			pb.width = 350;
			pb.move(100,120);
			pb.mode = ProgressBarMode.MANUAL;
			addChild(pb);

			_output = new TextField();
			_output.width = 400;
			_output.height = 400;
			_output.y = 180;
			_output.x = 40;
			_output.multiline = true;
			_output.wordWrap = true;
			_output.autoSize = TextFieldAutoSize.LEFT;
			addChild(_output);
			_fileReference = new FileReference();
			_fileReference.addEventListener(Event.SELECT, selectHandler);
			_fileReference.addEventListener(Event.CANCEL, cancelHandler);
			_fileReference.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			_fileReference.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_fileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityHandler);
			
		}
		private function browseHandler(event:MouseEvent):void
		{
			_fileReference.browse([new FileFilter("Pliki obrazów: *.jpg,*.png,*.bmp,*.gif","*.jpg;*.gif;*.png;*.bmp")]);
			_fileReference.addEventListener(Event.COMPLETE, onFileLoaded);
		}
		private function selectHandler(event:Event):void
		{

			_upload.visible = true;
			_fileReference.load();
		}
		function onFileLoaded(e:Event):void
		{
			loader= new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, placeImage);
			loader.loadBytes(e.target.data);			
			_fileReference.removeEventListener(Event.COMPLETE,onFileLoaded);
		}
		function placeImage(o:Event):void
		{
			pictureWidth = loader.width;
			pictureHeight = loader.height;
			infoFormat.color = 0x000000;
			_output.text="Wybrany plik";
			_output.appendText("\nNazwa: " + _fileReference.name);
			
			if (_fileReference.size / (1024 * 1024) > 4)
			{
				infoFormat.color = 0xFF0000;
				_output.appendText("\nPlik może mieć maksymalnie rozmiar 4MB");
				_upload.visible = false;
			}
			_output.setTextFormat(infoFormat);
			pb.setProgress(0,100);
			percentText.text = "";
			_output.appendText("\nRozmiar: " + formatSize(_fileReference.size)+" ("+pictureWidth+"x"+pictureHeight+" px)");
			if (pictureWidth<800 && pictureHeight)
			{
				infoFormat.color = 0xFF0000;
				_output.appendText("\nostrzeżenie: Ten plik zostanie powiększony \nprzez co może być rozmazany");
			}
		}
		private function cancelHandler(event:Event):void
		{
			_output.text = "Anulowano";
			_output.setTextFormat(infoFormat);
			_upload.visible = false;
		}
		private function uploadHandler(event:MouseEvent):void
		{
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,placeImage);			
			_fileReference.upload(new URLRequest("/ajax/upload?time="+time.time+"&sellerid="+sellerid+"&shopname="+shopurl));
			_fileReference.addEventListener(Event.COMPLETE, completeHandler);
		}
		private function progressHandler(event:ProgressEvent):void
		{
			infoFormat.color = 0x000000;
			var _progress:Number = event.bytesLoaded / event.bytesTotal * 100;
			pb.setProgress(_progress,100);
			percentText.text = _progress.toFixed() + "%";
			percentText.setTextFormat(infoFormat);
			addChild(percentText);
			if(_progress>99) 
			{				
				_output.text = "Trwa przetwarzanie pliku przez serwer";
				_output.setTextFormat(infoFormat);
			}
		}
		private function ioErrorHandler(event:IOErrorEvent):void
		{
			_output.text = "Wystąpił błąd wejścia/wyjścia\n"+event.toString();
		}
		private function securityHandler(event:SecurityErrorEvent):void
		{
			_output.text = "Wystąpił błąd bezpieczeństwa\n"+event.toString();
		}
		private function completeFileListener(event:Event):void
		{
			if (event.target.data=="ok")
			{
				_output.text="plik "+_fileReference.name+" został pomyślnie wysłany";
				infoFormat.color = 0x00FF00;				
			}
			else 
			{
				_output.text=event.target.data;
				infoFormat.color = 0xFF0000;
			}
			_output.setTextFormat(infoFormat);
			fileLoader.removeEventListener(Event.COMPLETE,completeFileListener);
			_fileReference.removeEventListener(Event.COMPLETE, completeHandler);
			new URLLoader(new URLRequest("/ajax/usun?time="+time.time));
		}
		private function completeHandler(event:Event):void
		{
			var request:URLRequest = new URLRequest("/"+time.time+".txt");
				fileLoader = new URLLoader(request);
				fileLoader.addEventListener(Event.COMPLETE, completeFileListener);				
			//_output.appendText("Plik został wysłany");
		}
	}
}